package com.example.campuslink.viewModel

import android.content.Intent
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.campuslink.commen.db.invitation.InvitationTable
import com.example.campuslink.commen.db.message.MessageTable
import com.example.campuslink.commen.db.userInfo.UserInfoTable
import com.example.campuslink.commen.db.userNumber.UserNumberTable
import com.example.campuslink.commen.enums.MessageTypeEnum
import com.example.campuslink.commen.enums.MineInvitationNowStatusEnum
import com.example.campuslink.commen.tools.Sp
import com.example.campuslink.commen.tools.SpKey
import com.example.campuslink.commen.tools.putExtraKey
import com.example.campuslink.ui.activity.FansAndAttentionActivity
import com.example.campuslink.ui.activity.InvitationDetailActivity
import com.example.campuslink.ui.activity.ScanActivity
import com.example.campuslink.ui.activity.userOperation.UserInfoActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MineViewModel : BaseViewModel() {
    private val _publicInvitationLiveData = MutableLiveData<MutableList<InvitationTable>>()
    val publicInvitationLiveData = _publicInvitationLiveData
    private val _collectionInvitationLiveData = MutableLiveData<MutableList<InvitationTable>>()
    val collectionInvitationLiveData = _collectionInvitationLiveData
    private val _lookInvitationLiveData = MutableLiveData<MutableList<InvitationTable>>()
    val lookInvitationLiveData = _lookInvitationLiveData
    private val _attentionInvitationLiveData = MutableLiveData<MutableList<String>>()
    val attentionInvitationLiveData = _attentionInvitationLiveData
    private val _fenSiteLiveData = MutableLiveData<MutableList<String>>()
    val fenSiteLiveData = _fenSiteLiveData
    lateinit var userNumberInfo: UserNumberTable
    private val _userInfo = MutableLiveData<UserInfoTable?>()
    val userInfo get() = _userInfo
    private val _nowInvitationType =
        MutableLiveData<String>(MineInvitationNowStatusEnum.PUBLIC.name)
    val nowInvitationType get() = _nowInvitationType
    private val _searchInvitationLiveData = MutableLiveData<MutableList<InvitationTable>>()
    val searchInvitationLiveData = _searchInvitationLiveData

    fun setInvitationType(type: String) {
        _nowInvitationType.value = type
    }

    fun unCollection(invitation: InvitationTable) {

        viewModelScope.launch(Dispatchers.IO) {
            val userNumber =
                userNumberDao.getUserNumber(Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: "")
            val schoolInfoTable =
                schoolInfoDao.getSchoolInfoBySchoolName(userNumber?.schoolName ?: "")
            invitation?.collectionThisInvitationNumber?.remove(
                Sp.getString(
                    context,
                    SpKey.USER_NUMBER.key,
                    ""
                ) ?: ""
            )
            userNumber?.collectList?.removeAll { it.id == invitation.id && it.userNumber == invitation.userNumber }
            userNumber?.browseList?.forEach {
                if (it.id == invitation.id && it.userNumber == invitation.userNumber) {
                    it.collectionThisInvitationNumber = invitation.collectionThisInvitationNumber
                    it.invitationParentCommend = invitation.invitationParentCommend
                    it.invitationChildrenCommend = invitation.invitationChildrenCommend
                }
            }

            userNumber?.publishList?.forEach {
                if (it.id == invitation.id && it.userNumber == invitation.userNumber) {
                    it.collectionThisInvitationNumber = invitation.collectionThisInvitationNumber
                    it.invitationParentCommend = invitation.invitationParentCommend
                    it.invitationChildrenCommend = invitation.invitationChildrenCommend
                }
            }
            invitationDao.updateInvitation(invitation ?: return@launch)
            userNumberDao.updateUserNumber(userNumber ?: return@launch)
            schoolInfoTable.mainInvitationList.forEach {
                if (it.id == invitation.id && it.userNumber == it.userNumber) {
                    it.collectionThisInvitationNumber = invitation.collectionThisInvitationNumber
                }
            }
            schoolInfoDao.updateSchoolInfo(schoolInfoTable)
            if (_nowInvitationType?.value == MineInvitationNowStatusEnum.PUBLIC.name) {
                getPublicInvitationList()
            } else if (_nowInvitationType?.value == MineInvitationNowStatusEnum.COLLECTION.name) {
                getCollectionInvitationList()
            } else {
                getLookInvitationList()
            }
        }
    }

    fun collection(invitation: InvitationTable) {

        viewModelScope.launch(Dispatchers.IO) {
            val userNumber =
                userNumberDao.getUserNumber(Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: "")
            val schoolInfoTable =
                schoolInfoDao.getSchoolInfoBySchoolName(userNumber?.schoolName ?: "")
            if (userNumber?.collectList == null) {
                userNumber?.collectList = mutableListOf()
            }
            if (invitation?.collectionThisInvitationNumber == null) {
                invitation?.collectionThisInvitationNumber = mutableListOf()
            }
            if (schoolInfoTable?.messageList == null) {
                schoolInfoTable?.messageList = mutableListOf()
            }
//            userNumber?.collectList?.remove(invitation)
            userNumber?.collectList?.removeAll { it.id == invitation.id && it.userNumber == invitation.userNumber }
            invitation?.collectionThisInvitationNumber?.remove(
                Sp.getString(
                    context,
                    SpKey.USER_NUMBER.key,
                    ""
                ) ?: ""
            )

            if (invitation?.userNumber != Sp.getString(context, SpKey.USER_NUMBER.key, "")) {
                var messageTable = MessageTable()
//                messageTable.id = messageDao.getMaxId() ?: 0 + 1
                messageTable.messageImage = invitation?.invitationImage?.get(0) ?: ""
                messageTable.invitationId = invitation?.id ?: 0
                messageTable.messageTime = System.currentTimeMillis()
                messageTable.messageType = MessageTypeEnum.BE_LOVE_INVITATION.value
                messageTable.sendNumber = Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: ""
                messageTable.handNumber = invitation?.userNumber ?: ""
                messageTable.messageContent =
                    "用户${Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: ""}收藏了你的帖子"
                messageDao.insertMessage(messageTable)
                schoolInfoTable?.messageList?.add(messageTable)
                schoolInfoDao.updateSchoolInfo(schoolInfoTable ?: return@launch)
            }



            userNumber?.collectList?.add(invitation)
            invitation?.collectionThisInvitationNumber?.add(
                Sp.getString(
                    context,
                    SpKey.USER_NUMBER.key,
                    ""
                ) ?: ""
            )
            invitationDao.updateInvitation(invitation ?: return@launch)
            userNumberDao.updateUserNumber(userNumber ?: return@launch)
            schoolInfoTable.mainInvitationList.forEach {

                if (it.id == invitation.id && it.userNumber == it.userNumber) {
                    Log.i("TAG", "collection: ${it}")
                    it.collectionThisInvitationNumber = invitation.collectionThisInvitationNumber
                    Log.i("TAG", "collection: ${it}")
                }
            }
            userNumber?.browseList?.forEach {
                if (it.id == invitation.id && it.userNumber == invitation.userNumber) {
//                    userNumber?.browseList?.remove(it)
//                    userNumber?.browseList?.add(invitation)
                    it.collectionThisInvitationNumber = invitation.collectionThisInvitationNumber
                    it.invitationParentCommend = invitation.invitationParentCommend
                    it.invitationChildrenCommend = invitation.invitationChildrenCommend
                }
            }

            userNumber?.publishList?.forEach {
                if (it.id == invitation.id && it.userNumber == invitation.userNumber) {
//                    it.copy()
//                    it.copy(collectionThisInvitationNumber = invitation.collectionThisInvitationNumber)
                    it.collectionThisInvitationNumber = invitation.collectionThisInvitationNumber
                    it.invitationParentCommend = invitation.invitationParentCommend
                    it.invitationChildrenCommend = invitation.invitationChildrenCommend
                }
            }
            userNumberDao?.updateUserNumber(userNumber ?: return@launch)
            schoolInfoDao.updateSchoolInfo(schoolInfoTable)

            if (_nowInvitationType?.value == MineInvitationNowStatusEnum.PUBLIC.name) {
                getPublicInvitationList()
            } else if (_nowInvitationType?.value == MineInvitationNowStatusEnum.COLLECTION.name) {
                getCollectionInvitationList()
            } else {
                getLookInvitationList()
            }

        }
    }

    fun addBrowser(invitation: InvitationTable) {
        viewModelScope.launch(Dispatchers.IO) {
            val userNumber =
                userNumberDao.getUserNumber(Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: "")
            if (userNumber?.browseList == null) {
                userNumber?.browseList = mutableListOf()
            }
            userNumber?.browseList?.removeAll { it.id == invitation.id && it.userNumber == invitation.userNumber }
            userNumber?.browseList?.add(invitation)
            userNumberDao.updateUserNumber(userNumber ?: return@launch)
        }
    }

    fun jumpToInvitationDetailActivity(invitation: InvitationTable) {
        Sp.setString(context, SpKey.INVITATION_NUMBER.key, invitation.userNumber)
        Sp.setInt(context, SpKey.INVITATION_ID.key, invitation.id)
        startActivity(Intent().apply {
            putExtra(putExtraKey.INVITATION.key, invitation)
        }, targetClass = InvitationDetailActivity::class.java)
    }

    fun jumpToFansAndAttentionActivity(jumpType: String) {
//        Sp.setString(
//            context,
//            SpKey.OTHER_NUMBER.key,
//            Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: ""
//        )
        startActivity(Intent().apply {
            putExtra(putExtraKey.JUMP_TYPE.key, jumpType)
            putExtra(putExtraKey.USER_NUMBER.key, Sp.getString(context, SpKey.USER_NUMBER.key, ""))
//            putExtra(putExtraKey.IS_FIRST_JUMP.key, true)
        }, targetClass = FansAndAttentionActivity::class.java)
    }

    fun jumpToScanActivity() {
        startActivity(Intent(), targetClass = ScanActivity::class.java)
    }

    fun jumpUserInfo() {
        startActivity(Intent(), targetClass = UserInfoActivity::class.java)
    }

    fun getPublicInvitationList() {
        viewModelScope.launch(Dispatchers.IO) {
            val numberInfo = userNumberDao.getUserNumber(
                Sp.getString(
                    context ?: return@launch,
                    "userNumber",
                    ""
                )!!
            )
            Log.i("getPublicInvitation", "getPublicInvitationList: ${numberInfo?.publishList}")
            if (numberInfo != null) {
                userNumberInfo = numberInfo
                val invitationList = numberInfo.publishList
                _publicInvitationLiveData.postValue(invitationList)
            }
        }
    }


    fun getSearchInvitation(type: String, search: String) {
        val temp = mutableListOf<InvitationTable>()
        viewModelScope.launch(Dispatchers.IO) {
            if (type == MineInvitationNowStatusEnum.PUBLIC.name) {
                if (search == "") {
                    _searchInvitationLiveData.postValue(
                        _publicInvitationLiveData.value ?: mutableListOf()
                    )
                } else {
                    _publicInvitationLiveData.value?.forEach {
                        if (it.invitationTitle.contains(search) ||
                            it.invitationType.contains(search) ||
                            it.invitationContent.contains(search)
                        ) {
                            temp.add(it)
                        }
                    }
                    _searchInvitationLiveData.postValue(temp)
                }


            } else if (type == MineInvitationNowStatusEnum.COLLECTION.name) {
                if (search == "") {
                    _searchInvitationLiveData.postValue(
                        _collectionInvitationLiveData.value ?: mutableListOf()
                    )
                } else {
                    _collectionInvitationLiveData.value?.forEach {
                        if (it.invitationTitle.contains(search) ||
                            it.invitationType.contains(search) ||
                            it.invitationContent.contains(search)
                        ) {
                            temp.add(it)
                        }
                    }
                    _searchInvitationLiveData.postValue(temp)
                }
            } else {
                if (search == "") {
                    _searchInvitationLiveData.postValue(
                        _lookInvitationLiveData.value ?: mutableListOf()
                    )
                } else {
                    _lookInvitationLiveData.value?.forEach {
                        if (it.invitationTitle.contains(search) ||
                            it.invitationType.contains(search) ||
                            it.invitationContent.contains(search)
                        ) {
                            temp.add(it)
                        }
                    }
                    _searchInvitationLiveData.postValue(temp)
                }
            }
        }
    }

    fun getUserInfo() {
        viewModelScope.launch(Dispatchers.IO) {
            val userNumber =
                Sp.getString(context ?: return@launch, "userNumber", "") ?: return@launch
            val tempUserInfo = userInfoDao?.getUserInfoByUserNumber(userNumber)

            if (tempUserInfo != null) {
                _userInfo.postValue(tempUserInfo)
            }
        }
    }

    fun getAttentionInvitationList() {
        viewModelScope.launch(Dispatchers.IO) {
            val numberInfo = userNumberDao.getUserNumber(
                Sp.getString(
                    context ?: return@launch,
                    "userNumber",
                    ""
                )!!
            )
            if (numberInfo != null) {
                userNumberInfo = numberInfo
                val invitationList = numberInfo.followList
                _attentionInvitationLiveData.postValue(invitationList)
            }
        }
    }

    fun getFenSiteList() {
        viewModelScope.launch(Dispatchers.IO) {
            val numberInfo = userNumberDao.getUserNumber(
                Sp.getString(
                    context ?: return@launch,
                    "userNumber",
                    ""
                )!!
            )
            if (numberInfo != null) {
                userNumberInfo = numberInfo
                val invitationList = numberInfo.fansList
                _fenSiteLiveData.postValue(invitationList)
            }
        }
    }

    fun getCollectionInvitationList() {
        viewModelScope.launch(Dispatchers.IO) {
            val numberInfo = userNumberDao.getUserNumber(
                Sp.getString(
                    context ?: return@launch,
                    "userNumber",
                    ""
                )!!
            )
            if (numberInfo != null) {
                userNumberInfo = numberInfo
                val invitationList = numberInfo.collectList
                _collectionInvitationLiveData.postValue(invitationList)
            }
        }
    }

    fun getLookInvitationList() {
        viewModelScope.launch(Dispatchers.IO) {
            val numberInfo = userNumberDao.getUserNumber(
                Sp.getString(
                    context ?: return@launch,
                    "userNumber",
                    ""
                )!!
            )
            if (numberInfo != null) {
                userNumberInfo = numberInfo
                val invitationList = numberInfo.browseList
                _lookInvitationLiveData.postValue(invitationList)
            }
        }
    }
}